//
//  LCProjectSelectViewController.swift
//  mggz
//
//  Created by 匀视网Mac on 2018/1/8.
//  Copyright © 2018年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import MJRefresh
import ObjectMapper
import Moya
class LCProjectSelectViewController: UIViewController {
    lazy var dataArray : [LCProjectListModel] = [LCProjectListModel]()
    @IBOutlet weak var tableView: UITableView!
    fileprivate var totalPage:Int?
    fileprivate var currentPage = 1
    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.delegate = self
        self.tableView.dataSource = self
        
        self.tableView.separatorInset = UIEdgeInsetsMake(0, 10, 0, 10)
        self.tableView.rowHeight = UITableViewAutomaticDimension
        self.tableView.estimatedRowHeight = 128
        self.tableView.separatorStyle = .none
        self.tableView.backgroundColor = UIColor.init(red: 233/255.0, green: 233/255.0, blue: 233/255.0, alpha: 1)
        view.backgroundColor = UIColor.init(red: 233/255.0, green: 233/255.0, blue: 233/255.0, alpha: 1)
        self.tableView.showsVerticalScrollIndicator = false
        self.tableView.showsHorizontalScrollIndicator = false
        
        self.navigationItem.title = "项目列表"
        
        self.tableView.register(UINib.init(nibName: "LCProjectCell", bundle: nil), forCellReuseIdentifier: "ProjectCell")
        let tableFooter = MJRefreshAutoNormalFooter { [unowned self] in
            self.getNextPage()
        }
        self.tableView.mj_footer = tableFooter
        
        self.getData()
    }
    
    func getData() {
        
        
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        self.currentPage = 1
        MWApiMainManager.request(.GetLCProjectListData(pageIndex: 1, pageSize: 25, IsShowFinish: false, DemandBaseMigrantWorkerID: "", AccountId: accountId)) { (result) in
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    return
                }
                
                guard (jsonString["State"]) as! String == "OK" else{
                    return
                }
                print(jsonString)
                
                guard  let resultDic : NSDictionary = jsonString["Result"] as? NSDictionary else{
                    return
                }
                guard  let resultArray : NSArray = resultDic["Items"] as? NSArray else{
                    return
                }
                if let totalList = resultDic["Total"] as? Int {
                    self.totalPage = (totalList/25)+1
                }
                self.dataArray = Mapper<LCProjectListModel>().mapArray(JSONObject: resultArray)!
                self.tableView.reloadData()
                
            }
        }
    }
    
    func getNextPage() {
        guard (self.totalPage != nil) else {
            return
        }
        if self.currentPage >= self.totalPage! {
            self.tableView.mj_footer.endRefreshingWithNoMoreData()
            return
        }
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        self.currentPage += 1
        print(currentPage)
        MWApiMainManager.request(.GetLCProjectListData(pageIndex: 1, pageSize: 25, IsShowFinish: false, DemandBaseMigrantWorkerID: "", AccountId: accountId)) { (result) in
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    return
                }
                
                guard (jsonString["State"]) as! String == "OK" else{
                    return
                }
                print(jsonString)
                
                guard  let resultDic : NSDictionary = jsonString["Result"] as? NSDictionary else{
                    return
                }
                guard  let resultArray : NSArray = resultDic["Items"] as? NSArray else{
                    return
                }
                var salaryArray = [LCProjectListModel].init()
                salaryArray = Mapper<LCProjectListModel>().mapArray(JSONObject: resultArray)!
                if salaryArray.count <= 0 {
                self.tableView.mj_footer.endRefreshingWithNoMoreData()
                    return
                }
                self.dataArray += salaryArray
                self.tableView.reloadData()
                self.tableView.mj_footer.endRefreshing()
            }
        }
    }
    

    override func viewWillAppear(_ animated: Bool) {
       
    }
    private func setupData(){
//        WWProgressHUD.showWithStatus("数据正在载入...")
//        ProjectListNetWork.projectList(pageIndex: 1, pageSize: 25, keyword: "", isShowApplying: false) { (response) in
//            if response.success {
//                self.dataArray = response.value!
//            }
//            else {
//                WWError(response.message)
//            }
//            WWProgressHUD.dismiss()
//            self.tableView .reloadData()
//        }
    }
}
extension LCProjectSelectViewController : UITableViewDelegate,UITableViewDataSource{
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if self.dataArray.count==0{
            self.tableView.isHidden = true
        }else{
            self.tableView.isHidden = false
        }
        return self.dataArray.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell : LCProjectCell = tableView.dequeueReusableCell(withIdentifier: "ProjectCell") as! LCProjectCell
        cell.setupDataWith(model: self.dataArray[indexPath.row])
        return cell
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 103;
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model : LCProjectListModel = self.dataArray[indexPath.row]
        ProjectListNetWork.updateSeletedState(model.MarketSupplyBaseID!, completionHandler: { (response) in
            if response {
                self.pushMainView()
            }
        })
    }
    private func pushMainView(){
        setupNotification()
        self.mm_drawerController.closeDrawer(animated: true) { (completion) in
            
        }
        self.navigationController?.popViewController(animated: true)
    }
    private func setupNotification(){
        
        let center = NotificationCenter.default
        let notificationName = NSNotification.Name.init(LCNotificationMainRefresh)
        center.post(name: notificationName, object: nil, userInfo: nil)
    }
    
}
